package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.controller.vo.ShowInfoVo;
import com.hunttown.mes.manage.service.MesEquipmentRepairManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.MesEquipmentRepairDTO;
import com.hunttown.mes.rpc.domain.enums.mes.repair.RepairStatusEnum;
import com.hunttown.mes.rpc.domain.query.MesEquipmentRepairDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-03-30 15:25:55
 */
@Controller
@RequestMapping(value = "/mes/equipment-repair")
public class MesEquipmentRepairController {

    private final static Logger logger = LoggerFactory.getLogger(MesEquipmentRepairController.class);

    private final MesEquipmentRepairManageService mesEquipmentRepairService;
    private final AnalysisManageManageService manageService;
    private final TransportOperateLogManageService logService;
    private final ModelService modelService;

    @Autowired
    public MesEquipmentRepairController(MesEquipmentRepairManageService mesEquipmentRepairService, AnalysisManageManageService manageService, TransportOperateLogManageService logService, ModelService modelService) {
        this.mesEquipmentRepairService = mesEquipmentRepairService;
        this.manageService = manageService;
        this.logService = logService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, MesEquipmentRepairDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<MesEquipmentRepairDTO> dataPage = mesEquipmentRepairService.getForPage(dtoQuery);

        for (MesEquipmentRepairDTO item : dataPage.getItems()) {
            item.setEquipName(modelService.getMesEquipName(item.getEquipId()));
            item.setFailureName(modelService.getCatalogName(item.getFailureId()));
            item.setReportCn(modelService.getManageName(item.getReportId()));
            item.setRepairCn(modelService.getManageName(item.getRepairId()));
            item.setStatusName(RepairStatusEnum.getEnumByKey(item.getStatus()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //设备列表
        modelService.getMesEquipmentPage(model);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"J-W-BXJL-BJ", "J-W-BXJL-SC", "J-W-BXJL-QTY"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "mes/equipment-repair/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        MesEquipmentRepairDTO obj;

        if (id > 0) {
            obj = mesEquipmentRepairService.getById(id);
        } else {
            obj = new MesEquipmentRepairDTO();
            obj.setId(0);
            obj.setReportTime(new Date());
            obj.setRepairTime(new Date());
            obj.setCompleteTime(new Date());
        }
        model.addAttribute("Obj", obj);

        //设备列表
        modelService.getMesEquipmentPage(model);

        //故障类型
        modelService.getCatalogListForRecursion(model, 32, "failureList");

        //报修人/维修人
        modelService.getManagerPage(model);

        //维修状态
        model.addAttribute("repairStatusList", RepairStatusEnum.getEnumList());

        return "mes/equipment-repair/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, MesEquipmentRepairDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //单选
            if (objDTO.getIsAffectProduction() == null) {
                objDTO.setIsAffectProduction(0);
            }

            //日期
            objDTO.setReportTime(DateConvertUtils.strToDate(objDTO.getReportTimeSr()));
            objDTO.setRepairTime(DateConvertUtils.strToDate(objDTO.getRepairTimeSr()));
            objDTO.setCompleteTime(DateConvertUtils.strToDate(objDTO.getCompleteTimeSr()));

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = mesEquipmentRepairService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = mesEquipmentRepairService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = mesEquipmentRepairService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = mesEquipmentRepairService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        MesEquipmentRepairDTO obj = new MesEquipmentRepairDTO();
        obj.setId(id);

        if (id > 0) {
            obj = mesEquipmentRepairService.getById(id);
        }
        mesEquipmentRepairService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //详情
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public String getInfo(Model model, Integer id) {

        //显示标题
        String showTitle = "未知";

        //数据
        ShowInfoVo vo;
        List<ShowInfoVo> dataList = new ArrayList<>();

        if (id != null && id > 0) {
            MesEquipmentRepairDTO obj = mesEquipmentRepairService.getById(id);

            if (obj != null) {
                showTitle = modelService.getMesEquipName(obj.getEquipId()) + "维修";

                vo = new ShowInfoVo();
                vo.setKey("编号ID");
                vo.setValue(obj.getId());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备名称");
                vo.setValue(modelService.getMesEquipName(obj.getEquipId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("故障类型");
                vo.setValue(modelService.getCatalogName(obj.getFailureId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("故障描述");
                vo.setValue(obj.getFailureDescription());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("是否影响生产");
                vo.setValue(obj.getIsAffectProduction() == 1 ? "是" : "否");
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("报&ensp;修&ensp;人");
                vo.setValue(modelService.getManageName(obj.getReportId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("报修时间");
                vo.setValue(obj.getReportTimeSr());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("备注说明");
                vo.setValue(obj.getRemark());
                dataList.add(vo);

                //第二列
                vo = new ShowInfoVo();
                vo.setKey("维&ensp;修&ensp;人");
                vo.setValue(modelService.getManageName(obj.getRepairId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("维修时间");
                vo.setValue(obj.getRepairTimeSr());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("完成时间");
                vo.setValue(obj.getCompleteTimeSr());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("维修结果");
                vo.setValue(RepairStatusEnum.getEnumByKey(obj.getStatus()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("维修过程");
                vo.setValue(obj.getRepairResult());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("补充说明");
                vo.setValue(obj.getRepairDescription());
                dataList.add(vo);

            }

            model.addAttribute("showTitle", showTitle);
            model.addAttribute("dataList", dataList);
        }

        return "show/getinfo-template";
    }

    //endregion

    //region 解决维修

    /**
     * 解决维修
     *
     * @param model model
     * @param id    ID
     * @return model
     */
    @RequestMapping(value = "/solveRepair", method = RequestMethod.POST)
    public String solveRepair(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        if (id > 0) {
            MesEquipmentRepairDTO obj = mesEquipmentRepairService.getById(id);
            obj.setStatus(1);

            if (obj != null && (obj.getRepairId() == null || obj.getRepairId() <= 0)) {
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                obj.setRepairId(curr_obj.getId());
            }

            model.addAttribute("repairObj", obj);
            modelService.getManagerPage(model);
            model.addAttribute("repairStatusList", RepairStatusEnum.getEnumList());
        }

        return "mes/equipment-repair/solve-repair-modal";
    }

    /**
     * 保存解决维修
     *
     * @param request           request
     * @param id                报修ID
     * @param repairId          解决人ID
     * @param status            解决状态
     * @param repairResult      解决经过
     * @param repairDescription 补充说明
     * @return json
     */
    @RequestMapping(value = "/saveSolveRepair", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveSolveRepair(HttpServletRequest request, Integer id, Integer repairId, Integer status, String repairResult, String repairDescription) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (id == null || id <= 0) {
            map.put("returnMessage", "报修信息保存异常！");
            return map;
        }

        if (repairId == null || repairId <= 0) {
            map.put("returnMessage", "请选择维修人！");
            return map;
        }

        if (StringUtils.isBlank(repairResult)) {
            map.put("returnMessage", "请填写维修过程！");
            return map;
        }

        MesEquipmentRepairDTO obj = mesEquipmentRepairService.getById(id);

        MesEquipmentRepairDTO update = new MesEquipmentRepairDTO();
        update.setId(id);
        update.setRepairId(repairId);
        update.setStatus(status);
        update.setRepairResult(repairResult);
        update.setRepairDescription(repairDescription);
        if (obj.getRepairTimeSr().equals("1990-01-01 00:00:00")) {
            update.setRepairTime(new Date());
        }
        if (status == 1) {
            update.setCompleteTime(new Date());
        }
        boolean isNext = mesEquipmentRepairService.updateInfoById(update);

        //region *** 更新信息完毕记录操作日志 ***
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        logService.insertSimple(1, 186, id, 2,
                "保存报修解决信息",
                (isNext ? "成功" : "失败") + "：" + repairResult,
                curr_obj.getId(),
                IpUtils.getClientIp(request),
                SystemUtils.getBrowserInfo(request));
        //endregion

        map.put("returnCode", 1);
        map.put("returnMessage", "报修解决成功！");

        return map;
    }

    //endregion
}